package com.hejia.bulbul.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hejia.alauda.entity.BankCard;
import com.hejia.alauda.entity.Order;
import com.hejia.alauda.entity.PayGate;
import com.hejia.alauda.entity.Product;
import com.hejia.alauda.service.ProductService;
import com.hejia.alauda.service.StatisticService;
import com.hejia.bulbul.utils.ExportUtil;

@Controller
@RequestMapping("stat")
public class StatController extends BaseController {

	@Resource
	private StatisticService statisticService;

	@Resource
	private ProductService productService;

	/**
	 * 单样产品统计
	 * 
	 * @param serial
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "stat/{serial}", method = RequestMethod.GET)
	public String statProduct(@PathVariable String serial, ModelMap model) {
		Product product = productService.getProductBySerial(serial);
		Long id = product.getId();
		Double averageAmount = (double) 0;

		/**
		 * 金额统计
		 */
		Double unpayAmount = statisticService.productTotalSales(id,
				Order.Status.STATUS_UNPAY);// 待付款金额
		Double paidAmount = statisticService.productTotalSales(id,
				Order.Status.STATUS_PAID);// 已付款金额
		Double overdueAmount = statisticService.productTotalSales(id,
				Order.Status.STATUS_OVERDUE);// 到期未付款金额
		Double failedAmount = statisticService.productTotalSales(id,
				Order.Status.STATUS_FAILED);// 支付失败金额
		Double excessAmount = statisticService.productTotalSales(id,
				Order.Status.STATUS_EXCESS);// 超额支付金额
		unpayAmount = unpayAmount != null ? unpayAmount : (double) 0;
		paidAmount = paidAmount != null ? paidAmount : (double) 0;
		overdueAmount = overdueAmount != null ? overdueAmount : (double) 0;
		failedAmount = failedAmount != null ? failedAmount : (double) 0;
		excessAmount = excessAmount != null ? excessAmount : (double) 0;

		/**
		 * 人数统计
		 */
		Integer allBuyers = statisticService.productNumOfBuyer(id, null);// 总购买人数
		Integer overdueBuyers = statisticService.productNumOfBuyer(id,
				Order.Status.STATUS_OVERDUE);// 到期未付款人数
		Integer unpayBuyers = statisticService.productNumOfBuyer(id,
				Order.Status.STATUS_UNPAY);// 待付款人数
		Integer paidBuyers = statisticService.productNumOfBuyer(id,
				Order.Status.STATUS_PAID);// 已付款人数
		Integer failedBuyers = statisticService.productNumOfBuyer(id,
				Order.Status.STATUS_FAILED);// 支付失败人数
		Integer excessBuyers = statisticService.productNumOfBuyer(id,
				Order.Status.STATUS_EXCESS);// 超额支付人数

		/**
		 * 订单数统计
		 */
		Integer allOrders = statisticService.productNumOfOrder(id, null);// 总订单数
		Integer overdueOrders = statisticService.productNumOfOrder(id,
				Order.Status.STATUS_OVERDUE);// 到期未付款订单数
		Integer unpayOrders = statisticService.productNumOfOrder(id,
				Order.Status.STATUS_UNPAY);// 待付款订单数
		Integer paidOrders = statisticService.productNumOfOrder(id,
				Order.Status.STATUS_PAID);// 已付款订单数
		Integer failedOrders = statisticService.productNumOfOrder(id,
				Order.Status.STATUS_FAILED);// 支付失败订单数
		Integer excessOrders = statisticService.productNumOfOrder(id,
				Order.Status.STATUS_EXCESS);// 超额支付订单数

		if (paidAmount == 0 || paidOrders == 0) {
			averageAmount = (double) 0;
		} else {
			BigDecimal PA = new BigDecimal(paidAmount);
			averageAmount = statisticService.selectPerAmount(PA, paidOrders);
		}

		model.put("product", product);
		model.put("perAmount", averageAmount);

		model.put("productUnpay", unpayAmount);
		model.put("productPaid", paidAmount);
		model.put("productOverdue", overdueAmount);
		model.put("productFailed", failedAmount);
		model.put("productExcess", excessAmount);

		model.put("productAllBuyer", allBuyers);
		model.put("productOverdueBuyer", overdueBuyers);
		model.put("productUnpayBuyer", unpayBuyers);
		model.put("productPaidBuyer", paidBuyers);
		model.put("productFailedBuyer", failedBuyers);
		model.put("productExcessBuyer", excessBuyers);

		model.put("productNumOfOrder", allOrders);
		model.put("productOverdueOrder", overdueOrders);
		model.put("productUnpayOrder", unpayOrders);
		model.put("productPaidOrder", paidOrders);
		model.put("productFailedOrder", failedOrders);
		model.put("productExcessOrder", excessOrders);

		return "/product/stat";
	}

	/**
	 * 产品统计（整体）（单日统计）
	 * 
	 * @param startTime
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "statall", method = RequestMethod.GET)
	public String statalldayTotalSales(String startTime, ModelMap model) {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		String statDate = null;
		if (startTime == null) {
			statDate = date.format(new Date());
		} else {
			statDate = startTime;
			model.put("msg", "c");
		}

		/**
		 * 金额统计
		 */
		Double totalAmount = statisticService.dayTotalSales(statDate);// 总金额
		Double overdueAmount = statisticService.dayTotalSales(statDate,
				Order.Status.STATUS_OVERDUE);// 到期未付款金额
		Double unpayAmount = statisticService.dayTotalSales(statDate,
				Order.Status.STATUS_UNPAY);// 待付款金额
		Double paidAmount = statisticService.dayTotalSales(statDate,
				Order.Status.STATUS_PAID);// 已付款金额
		Double failedAmount = statisticService.dayTotalSales(statDate,
				Order.Status.STATUS_FAILED);// 支付失败金融
		Double excessAmount = statisticService.dayTotalSales(statDate,
				Order.Status.STATUS_EXCESS);// 超额支付金额
		totalAmount = totalAmount != null ? totalAmount : (double) 0;
		overdueAmount = overdueAmount != null ? overdueAmount : (double) 0;
		unpayAmount = unpayAmount != null ? unpayAmount : (double) 0;
		paidAmount = paidAmount != null ? paidAmount : (double) 0;
		failedAmount = failedAmount != null ? failedAmount : (double) 0;
		excessAmount = excessAmount != null ? excessAmount : (double) 0;

		/**
		 * 人数统计
		 */
		Integer allBuyers = statisticService.numberOfBuyer(statDate);// 总购买人数
		Integer overdueBuyers = statisticService.numberOfBuyer(statDate,
				Order.Status.STATUS_OVERDUE);// 到期未付款人数
		Integer unpayBuyers = statisticService.numberOfBuyer(statDate,
				Order.Status.STATUS_UNPAY);// 暂时未付款人数
		Integer paidBuyers = statisticService.numberOfBuyer(statDate,
				Order.Status.STATUS_PAID);// 已经付款人数
		Integer failedBuyers = statisticService.numberOfBuyer(statDate,
				Order.Status.STATUS_FAILED);// 支付失败人数
		Integer excessBuyers = statisticService.numberOfBuyer(statDate,
				Order.Status.STATUS_EXCESS);// 超额支付人数

		/**
		 * 订单数统计
		 */
		Integer allOrders = statisticService.dayNumOfOrder(statDate);// 总订单数
		Integer overdueOrders = statisticService.dayNumOfOrder(statDate,
				Order.Status.STATUS_OVERDUE);// 到期未付款订单数
		Integer unpayOrders = statisticService.dayNumOfOrder(statDate,
				Order.Status.STATUS_UNPAY);// 暂时未付款订单数
		Integer paidOrders = statisticService.dayNumOfOrder(statDate,
				Order.Status.STATUS_PAID);// 已经付款订单数
		Integer failedOrders = statisticService.dayNumOfOrder(statDate,
				Order.Status.STATUS_FAILED);// 支付失败订单数
		Integer excessOrders = statisticService.dayNumOfOrder(statDate,
				Order.Status.STATUS_EXCESS);// 超额支付订单数

		model.put("dayTotalSales", totalAmount);
		model.put("dayOverdue", overdueAmount);
		model.put("dayUnpay", unpayAmount);
		model.put("dayPaid", paidAmount);
		model.put("dayFailed", failedAmount);
		model.put("dayExcess", excessAmount);

		model.put("numberOfBuyer", allBuyers);
		model.put("dayOverdueBuyer", overdueBuyers);
		model.put("dayUnpayBuyer", unpayBuyers);
		model.put("dayPaidBuyer", paidBuyers);
		model.put("dayFailedBuyer", failedBuyers);
		model.put("dayExcessBuyer", excessBuyers);

		model.put("dayNumOfOrder", allOrders);
		model.put("dayOverdueOrder", overdueOrders);
		model.put("dayUnpayOrder", unpayOrders);
		model.put("dayPaidOrder", paidOrders);
		model.put("dayFailedOrder", failedOrders);
		model.put("dayExcessOrder", excessOrders);

		model.put("startTime", statDate);

		return "/product/statall";
	}

	/**
	 * 产品统计（整体）（多日统计：昨日，7日，30日）
	 * 
	 * @param a
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "manydaysstatall/{a}", method = RequestMethod.GET)
	public String manyDaysStatall(@PathVariable Integer a, ModelMap model) {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		String statDate = date.format(new Date());
		if (a == 7) {
			cd.add(Calendar.DATE, -7);
			model.put("msg", "a");

		} else if (a == 30) {
			cd.add(Calendar.DATE, -30);
			model.put("msg", "b");

		} else {
			cd.add(Calendar.DATE, -1);
			model.put("msg", "d");

		}
		String statDate2 = date.format(cd.getTime());

		/**
		 * 金额统计
		 */
		Double totalAmount = statisticService.manyDaysTotalSales(statDate,
				statDate2, null);// 总金额
		Double overdueAmount = statisticService.manyDaysTotalSales(statDate,
				statDate2, Order.Status.STATUS_OVERDUE);// 到期未付款金额
		Double unpayAmount = statisticService.manyDaysTotalSales(statDate,
				statDate2, Order.Status.STATUS_UNPAY);// 待付款金额
		Double paidAmount = statisticService.manyDaysTotalSales(statDate,
				statDate2, Order.Status.STATUS_PAID);// 已付款金额
		Double failedAmount = statisticService.manyDaysTotalSales(statDate,
				statDate2, Order.Status.STATUS_FAILED);// 支付失败金融
		Double excessAmount = statisticService.manyDaysTotalSales(statDate,
				statDate2, Order.Status.STATUS_EXCESS);// 超额支付金融
		totalAmount = totalAmount != null ? totalAmount : (double) 0;
		overdueAmount = overdueAmount != null ? overdueAmount : (double) 0;
		unpayAmount = unpayAmount != null ? unpayAmount : (double) 0;
		paidAmount = paidAmount != null ? paidAmount : (double) 0;
		failedAmount = failedAmount != null ? failedAmount : (double) 0;
		excessAmount = excessAmount != null ? excessAmount : (double) 0;

		/**
		 * 人数统计
		 */
		Integer allBuyers = statisticService.manyDaysNumOfBuyer(statDate,
				statDate2, null);// 总购买人数
		Integer overdueBuyers = statisticService.manyDaysNumOfBuyer(statDate,
				statDate2, Order.Status.STATUS_OVERDUE);// 到期未付款人数
		Integer unpayBuyers = statisticService.manyDaysNumOfBuyer(statDate,
				statDate2, Order.Status.STATUS_UNPAY);// 暂时未付款人数
		Integer paidBuyers = statisticService.manyDaysNumOfBuyer(statDate,
				statDate2, Order.Status.STATUS_PAID);// 已经付款人数
		Integer failedBuyers = statisticService.manyDaysNumOfBuyer(statDate,
				statDate2, Order.Status.STATUS_FAILED);// 支付失败人数
		Integer excessBuyers = statisticService.manyDaysNumOfBuyer(statDate,
				statDate2, Order.Status.STATUS_EXCESS);// 超额支付人数

		/**
		 * 订单数统计
		 */
		Integer allOrders = statisticService.manyDaysNumOfOrder(statDate,
				statDate2, null);// 总订单数
		Integer overdueOrders = statisticService.manyDaysNumOfOrder(statDate,
				statDate2, Order.Status.STATUS_OVERDUE);// 到期未付订单数
		Integer unpayOrders = statisticService.manyDaysNumOfOrder(statDate,
				statDate2, Order.Status.STATUS_UNPAY);// 暂时未付款订单数
		Integer paidOrders = statisticService.manyDaysNumOfOrder(statDate,
				statDate2, Order.Status.STATUS_PAID);// 已经付款订单数
		Integer failedOrders = statisticService.manyDaysNumOfOrder(statDate,
				statDate2, Order.Status.STATUS_FAILED);// 支付失败订单数
		Integer excessOrders = statisticService.manyDaysNumOfOrder(statDate,
				statDate2, Order.Status.STATUS_EXCESS);// 超额支付订单数

		model.put("dayTotalSales", totalAmount);
		model.put("dayOverdue", overdueAmount);
		model.put("dayUnpay", unpayAmount);
		model.put("dayPaid", paidAmount);
		model.put("dayFailed", failedAmount);
		model.put("dayExcess", excessAmount);

		model.put("numberOfBuyer", allBuyers);
		model.put("dayOverdueBuyer", overdueBuyers);
		model.put("dayUnpayBuyer", unpayBuyers);
		model.put("dayPaidBuyer", paidBuyers);
		model.put("dayFailedBuyer", failedBuyers);
		model.put("dayExcessBuyer", excessBuyers);

		model.put("dayNumOfOrder", allOrders);
		model.put("dayOverdueOrder", overdueOrders);
		model.put("dayUnpayOrder", unpayOrders);
		model.put("dayPaidOrder", paidOrders);
		model.put("dayFailedOrder", failedOrders);
		model.put("dayExcessOrder", excessOrders);

		return "/product/statall";
	}

	/**
	 * 产品统计（整体）（全部统计）
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "alldaysstat", method = RequestMethod.GET)
	public String allDaysStat(ModelMap model) {

		/**
		 * 金额统计
		 */
		Double totalAmount = statisticService.allDaysTotalSales(null);// 总金额
		Double overdueAmount = statisticService
				.allDaysTotalSales(Order.Status.STATUS_OVERDUE);// 到期未付金额
		Double unpayAmount = statisticService
				.allDaysTotalSales(Order.Status.STATUS_UNPAY);// 待付款金额
		Double paidAmount = statisticService
				.allDaysTotalSales(Order.Status.STATUS_PAID);// 已付款金额
		Double failedAmount = statisticService
				.allDaysTotalSales(Order.Status.STATUS_FAILED);// 支付失败金额
		Double excessAmount = statisticService
				.allDaysTotalSales(Order.Status.STATUS_EXCESS);// 超额支付金额
		totalAmount = totalAmount != null ? totalAmount : (double) 0;
		overdueAmount = overdueAmount != null ? overdueAmount : (double) 0;
		unpayAmount = unpayAmount != null ? unpayAmount : (double) 0;
		paidAmount = paidAmount != null ? paidAmount : (double) 0;
		failedAmount = failedAmount != null ? failedAmount : (double) 0;
		excessAmount = excessAmount != null ? excessAmount : (double) 0;

		/**
		 * 人数统计
		 */
		Integer allBuyers = statisticService.allDaysNumOfBuyer(null);// 总购买人数
		Integer overdueBuyers = statisticService
				.allDaysNumOfBuyer(Order.Status.STATUS_OVERDUE);// 到期未付人数
		Integer unpayBuyers = statisticService
				.allDaysNumOfBuyer(Order.Status.STATUS_UNPAY);// 暂时未付款人数
		Integer paidBuyers = statisticService
				.allDaysNumOfBuyer(Order.Status.STATUS_PAID);// 已经付款人数
		Integer failedBuyers = statisticService
				.allDaysNumOfBuyer(Order.Status.STATUS_FAILED);// 支付失败人数
		Integer excessBuyers = statisticService
				.allDaysNumOfBuyer(Order.Status.STATUS_EXCESS);// 超额支付人数

		/**
		 * 订单数统计
		 */
		Integer allOrders = statisticService.allDaysNumOfOrder(null);// 总订单数
		Integer overdueOrders = statisticService
				.allDaysNumOfOrder(Order.Status.STATUS_OVERDUE);// 到期未付订单数
		Integer unpayOrders = statisticService
				.allDaysNumOfOrder(Order.Status.STATUS_UNPAY);// 暂时未付款订单数
		Integer paidOrders = statisticService
				.allDaysNumOfOrder(Order.Status.STATUS_PAID);// 已经付款订单数
		Integer failedOrders = statisticService
				.allDaysNumOfOrder(Order.Status.STATUS_FAILED);// 支付失败订单数
		Integer excessOrders = statisticService
				.allDaysNumOfOrder(Order.Status.STATUS_EXCESS);// 超额支付订单数

		model.put("dayTotalSales", totalAmount);
		model.put("dayOverdue", overdueAmount);
		model.put("dayUnpay", unpayAmount);
		model.put("dayPaid", paidAmount);
		model.put("dayFailed", failedAmount);
		model.put("dayExcess", excessAmount);

		model.put("numberOfBuyer", allBuyers);
		model.put("dayOverdueBuyer", overdueBuyers);
		model.put("dayUnpayBuyer", unpayBuyers);
		model.put("dayPaidBuyer", paidBuyers);
		model.put("dayFailedBuyer", failedBuyers);
		model.put("dayExcessBuyer", excessBuyers);

		model.put("dayNumOfOrder", allOrders);
		model.put("dayOverdueOrder", overdueOrders);
		model.put("dayUnpayOrder", unpayOrders);
		model.put("dayPaidOrder", paidOrders);
		model.put("dayFailedOrder", failedOrders);
		model.put("dayExcessOrder", excessOrders);
		model.put("msg", "c");
		model.put("param", "a");

		return "/product/statall";
	}

	/**
	 * 收支统计
	 * 
	 * @param a
	 * @param startTime
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "inoutstat/{a}", method = RequestMethod.GET)
	public String inOutStat(@PathVariable Integer a, String startTime,
			ModelMap model) {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		String regdate = date.format(new Date());

		cd.add(Calendar.DATE, -1);
		String oneDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String twoDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String threeDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String fourDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String fiveDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String sixDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String sevenDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -23);
		String thirtyDayAgo = date.format(cd.getTime());

		/**
		 * 收入统计
		 */
		Double todayOfIncome = statisticService.incomeAndExpense(regdate,
				regdate, "income");
		Double oneDayAgoOfIncome = statisticService.incomeAndExpense(oneDayAgo,
				oneDayAgo, "income");
		Double twoDayAgoOfIncome = statisticService.incomeAndExpense(twoDayAgo,
				twoDayAgo, "income");
		Double threeDayAgoOfIncome = statisticService.incomeAndExpense(
				threeDayAgo, threeDayAgo, "income");
		Double fourDayAgoOfIncome = statisticService.incomeAndExpense(
				fourDayAgo, fourDayAgo, "income");
		Double fiveDayAgoOfIncome = statisticService.incomeAndExpense(
				fiveDayAgo, fiveDayAgo, "income");
		Double sixDayAgoOfIncome = statisticService.incomeAndExpense(sixDayAgo,
				sixDayAgo, "income");
		Double sevenDayAgoOfIncome = statisticService.incomeAndExpense(
				sevenDayAgo, sevenDayAgo, "income");
		todayOfIncome = todayOfIncome != null ? todayOfIncome : (double) 0;
		oneDayAgoOfIncome = oneDayAgoOfIncome != null ? oneDayAgoOfIncome
				: (double) 0;
		twoDayAgoOfIncome = twoDayAgoOfIncome != null ? twoDayAgoOfIncome
				: (double) 0;
		threeDayAgoOfIncome = threeDayAgoOfIncome != null ? threeDayAgoOfIncome
				: (double) 0;
		fourDayAgoOfIncome = fourDayAgoOfIncome != null ? fourDayAgoOfIncome
				: (double) 0;
		fiveDayAgoOfIncome = fiveDayAgoOfIncome != null ? fiveDayAgoOfIncome
				: (double) 0;
		sixDayAgoOfIncome = sixDayAgoOfIncome != null ? sixDayAgoOfIncome
				: (double) 0;
		sevenDayAgoOfIncome = sevenDayAgoOfIncome != null ? sevenDayAgoOfIncome
				: (double) 0;

		/**
		 * 支出统计
		 */
		Double todayOfExpense = statisticService.incomeAndExpense(regdate,
				regdate, "expenses");
		Double oneDayAgoOfExpense = statisticService.incomeAndExpense(
				oneDayAgo, oneDayAgo, "expenses");
		Double twoDayAgoOfExpense = statisticService.incomeAndExpense(
				twoDayAgo, twoDayAgo, "expenses");
		Double threeDayAgoOfExpense = statisticService.incomeAndExpense(
				threeDayAgo, threeDayAgo, "expenses");
		Double fourDayAgoOfExpense = statisticService.incomeAndExpense(
				fourDayAgo, fourDayAgo, "expenses");
		Double fiveDayAgoOfExpense = statisticService.incomeAndExpense(
				fiveDayAgo, fiveDayAgo, "expenses");
		Double sixDayAgoOfExpense = statisticService.incomeAndExpense(
				sixDayAgo, sixDayAgo, "expenses");
		Double sevenDayAgoOfExpense = statisticService.incomeAndExpense(
				sevenDayAgo, sevenDayAgo, "expenses");
		todayOfExpense = todayOfExpense != null ? todayOfExpense : (double) 0;
		oneDayAgoOfExpense = oneDayAgoOfExpense != null ? oneDayAgoOfExpense
				: (double) 0;
		twoDayAgoOfExpense = twoDayAgoOfExpense != null ? twoDayAgoOfExpense
				: (double) 0;
		threeDayAgoOfExpense = threeDayAgoOfExpense != null ? threeDayAgoOfExpense
				: (double) 0;
		fourDayAgoOfExpense = fourDayAgoOfExpense != null ? fourDayAgoOfExpense
				: (double) 0;
		fiveDayAgoOfExpense = fiveDayAgoOfExpense != null ? fiveDayAgoOfExpense
				: (double) 0;
		sixDayAgoOfExpense = sixDayAgoOfExpense != null ? sixDayAgoOfExpense
				: (double) 0;
		sevenDayAgoOfExpense = sevenDayAgoOfExpense != null ? sevenDayAgoOfExpense
				: (double) 0;

		model.put("todayOfIncome", todayOfIncome);
		model.put("oneDayAgoOfIncome", oneDayAgoOfIncome);
		model.put("twoDayAgoOfIncome", twoDayAgoOfIncome);
		model.put("threeDayAgoOfIncome", threeDayAgoOfIncome);
		model.put("fourDayAgoOfIncome", fourDayAgoOfIncome);
		model.put("fiveDayAgoOfIncome", fiveDayAgoOfIncome);
		model.put("sixDayAgoOfIncome", sixDayAgoOfIncome);
		model.put("sevenDayAgoOfIncome", sevenDayAgoOfIncome);

		model.put("todayOfExpense", todayOfExpense);
		model.put("oneDayAgoOfExpense", oneDayAgoOfExpense);
		model.put("twoDayAgoOfExpense", twoDayAgoOfExpense);
		model.put("threeDayAgoOfExpense", threeDayAgoOfExpense);
		model.put("fourDayAgoOfExpense", fourDayAgoOfExpense);
		model.put("fiveDayAgoOfExpense", fiveDayAgoOfExpense);
		model.put("sixDayAgoOfExpense", sixDayAgoOfExpense);
		model.put("sevenDayAgoOfExpense", sevenDayAgoOfExpense);

		if (a == 100) {
			/**
			 * 全部收支统计
			 */
			Double allincome = (statisticService
					.allIncomeAndExpense("allincome") != null) ? statisticService
					.allIncomeAndExpense("allincome") : (double) 0;// 总收入
			Double allexpenses = (statisticService
					.allIncomeAndExpense("allexpenses") != null) ? statisticService
					.allIncomeAndExpense("allexpenses") : (double) 0;// 总支出

			Integer allpersons = statisticService.paymentPersons(null, null);
			model.put("income", allincome);
			model.put("expenses", allexpenses);
			model.put("persons", allpersons);
			model.put("msg", "c");
			model.put("param", "a");
		} else {
			/**
			 * 多日收支统计（昨日，7日，30日）
			 */
			String enddate = null;
			if (a == 7) {
				enddate = sevenDayAgo;
				model.put("msg", "a");

			} else if (a == 30) {
				enddate = thirtyDayAgo;
				model.put("msg", "b");

			} else if (a == 1) {
				regdate = oneDayAgo;
				enddate = oneDayAgo;
				model.put("msg", "d");

			} else if (a == 0) {
				enddate = regdate;

			} else {
				regdate = startTime;
				enddate = startTime;
				model.put("msg", "c");

			}

			Double income = statisticService.incomeAndExpense(regdate, enddate,
					"income");
			Double expenses = statisticService.incomeAndExpense(regdate,
					enddate, "expenses");
			Integer persons = statisticService.paymentPersons(regdate, enddate);
			income = income != null ? income : (double) 0;
			expenses = expenses != null ? expenses : (double) 0;

			model.put("income", income);
			model.put("expenses", expenses);
			model.put("persons", persons);

			model.put("startTime", regdate);
		}

		return "/product/inoutstat";
	}

	/**
	 * 用户统计
	 * 
	 * @param a
	 * @param startTime
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "reg/{a}", method = RequestMethod.GET)
	public String register(@PathVariable Integer a, String startTime,
			ModelMap model) {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		String regdate = date.format(new Date());
		String paramdate = date.format(new Date());

		cd.add(Calendar.DATE, -1);
		String oneDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String twoDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String threeDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String fourDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String fiveDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String sixDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -1);
		String sevenDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -23);
		String thirtyDayAgo = date.format(cd.getTime());

		/**
		 * 注册人数（图表用）
		 */
		Integer todayOfRegister = statisticService.dayNumOfUser(regdate);// 今日注册人数
		Integer oneDayAgoOfRegister = statisticService.dayNumOfUser(oneDayAgo);// 1日前注册人数
		Integer twoDayAgoOfRegister = statisticService.dayNumOfUser(twoDayAgo);// 2日前注册人数
		Integer threeDayAgoOfRegister = statisticService
				.dayNumOfUser(threeDayAgo);// 3日前注册人数
		Integer fourDayAgoOfRegister = statisticService
				.dayNumOfUser(fourDayAgo);// 4日前注册人数
		Integer fiveDayAgoOfRegister = statisticService
				.dayNumOfUser(fiveDayAgo);// 5日前注册人数
		Integer sixDayAgoOfRegister = statisticService.dayNumOfUser(sixDayAgo);// 6日前注册人数
		Integer sevenDayAgoOfRegister = statisticService
				.dayNumOfUser(sevenDayAgo);// 7日前注册人数

		model.put("dayNumOfUser", todayOfRegister);
		model.put("yestNumOfUser", oneDayAgoOfRegister);
		model.put("befNumOfUser", twoDayAgoOfRegister);
		model.put("threeNumOfUser", threeDayAgoOfRegister);
		model.put("fourNumOfUser", fourDayAgoOfRegister);
		model.put("fiveNumOfUser", fiveDayAgoOfRegister);
		model.put("sixNumOfUser", sixDayAgoOfRegister);
		model.put("sevenNumOfUser", sevenDayAgoOfRegister);

		if (a == 100) {
			/**
			 * 全部统计
			 */
			Integer allRegister = statisticService.numberOfUser();// 所有注册人数
			Integer allNumOfBuyers = statisticService.numOfPersons(null, null,
					null);// 所有购买人数
			Integer allTwiceBuyers = statisticService.numOfPersons(null, null,
					"alltwiceBuyers");// 所有二次购买人数
			Integer allRedeemBuyers = statisticService.numOfPersons(null, null,
					"allredeemBuyers");// 所有赎回再购买人数
			Integer allFifteenBuyers = statisticService.numOfPersons(null,
					null, "allFifteenBuyers");// 所以购买金额超过1500的人数

			model.put("registerNum", allRegister);
			model.put("numOfBuyers", allNumOfBuyers);
			model.put("newOfBuyers", allNumOfBuyers);
			model.put("registerBuyers", allNumOfBuyers);
			model.put("twiceBuyers", allTwiceBuyers);
			model.put("redeemBuyers", allRedeemBuyers);
			model.put("fifteenBuyers", allFifteenBuyers);
			model.put("msg", "c");
			model.put("param", "a");

		} else {
			/**
			 * 多日统计（昨日，7日，30日）
			 */
			String enddate = null;
			if (a == 7) {
				enddate = sevenDayAgo;
				model.put("msg", "a");

			} else if (a == 30) {
				enddate = thirtyDayAgo;
				model.put("msg", "b");

			} else if (a == 1) {
				regdate = oneDayAgo;
				enddate = oneDayAgo;
				model.put("msg", "d");

			} else if (a == 0) {
				enddate = regdate;

			} else {
				regdate = startTime;
				enddate = startTime;
				model.put("msg", "c");

			}

			Integer numOfRegister = null;
			if (enddate.equals(regdate) && regdate.equals(paramdate)) {
				numOfRegister = todayOfRegister;
			} else if (enddate.equals(regdate) && enddate.equals(oneDayAgo)) {
				numOfRegister = oneDayAgoOfRegister;
			} else {
				numOfRegister = statisticService.dayNumOfUser(regdate, enddate);// 注册人数
			}
			Integer numOfBuyers = statisticService.numOfPersons(regdate,
					enddate, "numOfBuyers");// 购买人数
			Integer numOfNewBuyers = statisticService.numOfPersons(regdate,
					enddate, "newOfBuyers");// 新增购买人数
			Integer registerBuyers = statisticService.numOfPersons(regdate,
					enddate, "registerBuyers");// 注册购买人数
			Integer twiceBuyers = statisticService.numOfPersons(regdate,
					enddate, "twiceBuyers");// 二次购买人数
			Integer redeemBuyers = statisticService.numOfPersons(regdate,
					enddate, "redeemBuyers");// 赎回再购买人数
			Integer fifteenBuyers = statisticService.numOfPersons(regdate,
					enddate, "fifteenBuyers");// 购买金额超过1500的人数

			/**
			 * 页面所需数据
			 */
			model.put("registerNum", numOfRegister);
			model.put("numOfBuyers", numOfBuyers);
			model.put("newOfBuyers", numOfNewBuyers);
			model.put("registerBuyers", registerBuyers);
			model.put("twiceBuyers", twiceBuyers);
			model.put("redeemBuyers", redeemBuyers);
			model.put("fifteenBuyers", fifteenBuyers);
			model.put("startTime", enddate);

		}

		return "/user/userregister";
	}

	/**
	 * 得到网站数据
	 * 
	 * @param startTime
	 * @param endTime
	 * @return
	 * @throws ParseException
	 */
	public Map<String, Map<String, Map<String, Object>>> getWebsiteData(
			String start, String end, String rate) throws ParseException {

		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		long date1 = date.parse(start).getTime();
		long date2 = date.parse(end).getTime();
		String[] sources = { "Web", "H5", "IOS", "Android", "All" };

		/*
		 * 分平台数据
		 */
		List<Map<String, Object>> successuserList = statisticService
				.statOperationIndex(start, end, "successuser");// 成功交易用户数
		List<Map<String, Object>> newsuccessuserList = statisticService
				.statOperationIndex(start, end, "newsuccessuser");// 新增成功交易用户
		List<Map<String, Object>> orderList = statisticService
				.statOperationIndex(start, end, "order");// 下单数总量
		List<Map<String, Object>> successorderList = statisticService
				.statOperationIndex(start, end, "successorder");// 成功交易订单
		List<Map<String, Object>> userList = statisticService
				.statOperationIndex(start, end, "user");// 提交用户数
		List<Map<String, Object>> saleList = statisticService
				.statOperationIndex(start, end, "sale");// 交易金额
		List<Map<String, Object>> registerList = statisticService
				.statOperationIndex(start, end, "register");// 注册人数
		List<Map<String, Object>> certifyusersList = statisticService
				.statOperationIndex(start, end, "certifyusers");// 认证人数

		/*
		 * 总和数据
		 */
		List<Map<String, Object>> allsuccessuserList = statisticService
				.statOperationIndex(start, end, "allsuccessuser");// 成功交易用户数
		List<Map<String, Object>> allnewsuccessuserList = statisticService
				.statOperationIndex(start, end, "allnewsuccessuser");// 新增成功交易用户
		List<Map<String, Object>> allorderList = statisticService
				.statOperationIndex(start, end, "allorder");// 下单数总量
		List<Map<String, Object>> allsuccessorderList = statisticService
				.statOperationIndex(start, end, "allsuccessorder");// 成功交易订单
		List<Map<String, Object>> alluserList = statisticService
				.statOperationIndex(start, end, "alluser");// 提交用户数
		List<Map<String, Object>> allsaleList = statisticService
				.statOperationIndex(start, end, "allsale");// 交易金额
		List<Map<String, Object>> allregisterList = statisticService
				.statOperationIndex(start, end, "allregister");// 注册人数
		List<Map<String, Object>> allcertifyusersList = statisticService
				.statOperationIndex(start, end, "allcertifyusers");// 认证人数

		String DAUS = null;// 提交用户数
		String DAU = null;// 成功交易用户数
		String NDAU = null;// 新增成功交易用户
		String ORD = null;// 下单数总量
		String SORD = null;// 成功交易订单
		String SAL = null;// 交易金额
		String RSTER = null;// 注册人数
		String CUSER = null;// 认证人数

		Map<String, Map<String, Map<String, Object>>> rest = new LinkedHashMap<String, Map<String, Map<String, Object>>>();
		for (long j = date2; j >= date1; j -= 24 * 60 * 60 * 1000) {
			Date date3 = new Date(j);
			String realdate = date.format(date3);
			Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
			for (int i = 0; i < sources.length; i++) {
				Map<String, Object> valueMap = new HashMap<String, Object>();

				if ("All".equals(sources[i])) {

					DAUS = getIndex(alluserList, realdate);// 提交用户数
					DAU = getIndex(allsuccessuserList, realdate);// 成功交易用户数
					NDAU = getIndex(allnewsuccessuserList, realdate);// 新增成功交易用户
					ORD = getIndex(allorderList, realdate);// 下单数总量
					SORD = getIndex(allsuccessorderList, realdate);// 成功交易订单
					SAL = getIndex(allsaleList, realdate);// 交易金额
					RSTER = getIndex(allregisterList, realdate);// 注册人数
					CUSER = getIndex(allcertifyusersList, realdate);// 认证人数

				} else {
					DAUS = getIndex(userList, realdate, sources[i]);// 提交用户数
					DAU = getIndex(successuserList, realdate, sources[i]);// 成功交易用户数
					NDAU = getIndex(newsuccessuserList, realdate, sources[i]);// 新增成功交易用户
					ORD = getIndex(orderList, realdate, sources[i]);// 下单数总量
					SORD = getIndex(successorderList, realdate, sources[i]);// 成功交易订单
					SAL = getIndex(saleList, realdate, sources[i]);// 交易金额
					RSTER = getIndex(registerList, realdate);// 注册人数
					CUSER = getIndex(certifyusersList, realdate);// 认证人数
				}

				if (Integer.parseInt(ORD) == 0 || Integer.parseInt(SORD) == 0) {
					rate = "0%";
				} else {
					BigDecimal number1 = new BigDecimal(ORD);
					BigDecimal number2 = new BigDecimal(SORD);
					Double rateNum = number2
							.divide(number1, 4, BigDecimal.ROUND_HALF_UP)
							.movePointRight(2).doubleValue();
					rate = rateNum + "%";
				}

				valueMap.put("DAU", DAU);
				valueMap.put("newDAU", NDAU);
				valueMap.put("allOrders", ORD);
				valueMap.put("successOfOrder", SORD);
				valueMap.put("allBuyer", DAUS);
				valueMap.put("rate", rate);
				valueMap.put("allSales", SAL);
				valueMap.put("allUsers", RSTER);
				valueMap.put("certifyUsers", CUSER);

				map.put(sources[i], valueMap);
			}
			rest.put(realdate, map);
		}
		return rest;
	}

	/**
	 * 得到产品数据
	 * 
	 * @param start
	 * @param end
	 * @param rate
	 * @return
	 * @throws ParseException
	 */
	public Map<String, Map<String, Map<String, Object>>> getProductData(
			String start, String end, String successrate) throws ParseException {

		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		long date1 = date.parse(start).getTime();
		long date2 = date.parse(end).getTime();

		List<Map<String, Object>> timesList = statisticService.productAnalyse(
				start, end, "times");// 交易次数
		List<Map<String, Object>> successtimesList = statisticService
				.productAnalyse(start, end, "successtimes");// 成功交易次数
		List<Map<String, Object>> buyerList = statisticService.productAnalyse(
				start, end, "buyer");// 交易用户数
		List<Map<String, Object>> successbuyerList = statisticService
				.productAnalyse(start, end, "successbuyer");// 成功交易用户数
		List<Map<String, Object>> prosalesList = statisticService
				.productAnalyse(start, end, "prosales");// 交易金额

		List<Product> products = statisticService.allProductByDate(start, end);

		String DLT = null;// 交易次数
		String SDLT = null;// 成功交易次数
		String DLUSER = null;// 交易用户数
		String SDLUSER = null;// 成功交易用户数
		String DLSALE = null;// 交易金额
		Double PARUP = null;// 人均ARUP

		Map<String, Map<String, Map<String, Object>>> rest = new LinkedHashMap<String, Map<String, Map<String, Object>>>();
		for (long j = date2; j >= date1; j -= 24 * 60 * 60 * 1000) {
			Date date3 = new Date(j);
			String realdate = date.format(date3);
			Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
			for (int i = 0; i < products.size(); i++) {
				Map<String, Object> valueMap = new HashMap<String, Object>();

				DLT = getProIndex(timesList, realdate, products.get(i).getId()
						.toString());// 交易次数
				SDLT = getProIndex(successtimesList, realdate, products.get(i)
						.getId().toString());// 成功交易次数
				DLUSER = getProIndex(buyerList, realdate, products.get(i)
						.getId().toString());// 交易用户数
				SDLUSER = getProIndex(successbuyerList, realdate,
						products.get(i).getId().toString());// 成功交易用户数
				DLSALE = getProIndex(prosalesList, realdate, products.get(i)
						.getId().toString());// 交易金额

				if ("0".equals(DLT) || "0".equals(SDLT)) {
					successrate = "0%";
				} else {
					BigDecimal number1 = new BigDecimal(DLT);
					BigDecimal number2 = new BigDecimal(SDLT);
					Double rateNum = number2
							.divide(number1, 4, BigDecimal.ROUND_HALF_UP)
							.movePointRight(2).doubleValue();
					successrate = rateNum + "%";
				}

				if ("0".equals(DLSALE) || "0".equals(SDLUSER)) {
					PARUP = (double) 0;
				} else {
					BigDecimal productPaidAll = new BigDecimal(DLSALE);
					PARUP = statisticService.selectPerAmount(productPaidAll,
							Integer.parseInt(SDLUSER));
				}

				valueMap.put("dealTimesAnalyse", DLT);
				valueMap.put("successTimesAnalyse", SDLT);
				valueMap.put("dealSalesAnalyse", DLSALE);
				valueMap.put("successBuyersAnalyse", SDLUSER);
				valueMap.put("dealBuyersAnalyse", DLUSER);
				valueMap.put("perARUP", PARUP);
				valueMap.put("successrate", successrate);

				map.put(products.get(i).getName(), valueMap);
			}
			rest.put(realdate, map);
		}
		return rest;
	}

	/**
	 * 循环获取某天某个渠道的数据
	 * 
	 * @param list
	 * @param date
	 * @param source
	 * @return
	 */
	private String getIndex(List<Map<String, Object>> list, String date,
			String source) {
		for (int i = 0; list != null && i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			if (map.get("xdate").equals(date)
					&& map.get("source").equals(source)) {
				return map.get("num").toString();
			}
		}
		return "0";
	}

	/**
	 * 循环获取某天某个渠道的数据
	 * 
	 * @param list
	 * @param date
	 * @param source
	 * @return
	 */
	private String getIndex(List<Map<String, Object>> list, String date) {
		for (int i = 0; list != null && i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			if (map.get("xdate") != null && map.get("xdate").equals(date)) {
				return map.get("num").toString();
			}
		}
		return "0";
	}

	/**
	 * 循环获取某个支付网关某个银行的数据
	 * 
	 * @param list
	 * @param date
	 * @param source
	 * @return
	 */
	private String getPGIndex(List<Map<String, Object>> list, String pgc,
			String bc) {
		for (int i = 0; list != null && i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			if (map.get("pgc").equals(pgc) && map.get("bc").equals(bc)) {
				return map.get("num").toString();
			}
		}
		return "0";
	}

	/**
	 * 循环获取某个支付网关的数据
	 * 
	 * @param list
	 * @param date
	 * @param source
	 * @return
	 */
	private String getPGIndex(List<Map<String, Object>> list, String pgc) {
		for (int i = 0; list != null && i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			if (map.get("pgc").equals(pgc)) {
				return map.get("num").toString();
			}
		}
		return "0";
	}

	/**
	 * 循环获取某天某个产品的数据
	 * 
	 * @param list
	 * @param date
	 * @param source
	 * @return
	 */
	private String getProIndex(List<Map<String, Object>> list, String date,
			String pid) {
		for (int i = 0; list != null && i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			if (map.get("xdate").equals(date)
					&& (map.get("pid").toString()).equals(pid)) {
				return map.get("num").toString();
			}
		}
		return "0";
	}

	/**
	 * 网站数据分析
	 * 
	 * @param startTime
	 * @param endTime
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "websiteanalyse", method = RequestMethod.GET)
	public String dayToAnalyse(String startTime, String endTime, ModelMap model)
			throws ParseException {

		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		String rate = null;
		String start = startTime;
		String end = endTime;
		if (startTime == null || endTime == null) {
			start = date.format(new Date());
			end = date.format(new Date());
		}

		Map<String, Map<String, Map<String, Object>>> rest = getWebsiteData(
				start, end, rate);

		model.addAttribute("result", rest);
		model.put("startTime", start);
		model.put("endTime", end);

		return "/product/websiteanalyse";
	}

	/**
	 * 产品数据分析
	 * 
	 * @param startTime
	 * @param endTime
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "productanalyse", method = RequestMethod.GET)
	public String dayForAnalyse(String startTime, String endTime, ModelMap model)
			throws ParseException {

		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		String successrate = null;
		String start = startTime;
		String end = endTime;
		if (startTime == null || endTime == null) {
			start = date.format(new Date());
			end = date.format(new Date());
		}

		List<Product> products = statisticService.allProductByDate(start, end);
		Map<String, Map<String, Map<String, Object>>> rest = getProductData(
				start, end, successrate);

		model.put("productNameList", products);
		model.addAttribute("result", rest);
		model.put("startTime", start);
		model.put("endTime", end);

		return "/product/productanalyse";
	}

	/**
	 * 保有量现状
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "inventory", method = RequestMethod.GET)
	public String inventory(ModelMap model) {

		/**
		 * 当前保有量
		 */
		Double income = statisticService.allIncomeAndExpense("allincome");
		Double expenses = statisticService.allIncomeAndExpense("expen");
		Double inven = statisticService.allIncomeAndExpense("inven");
		income = income != null ? income : (double) 0;
		expenses = expenses != null ? expenses : (double) 0;
		inven = inven != null ? inven : (double) 0;
		model.put("income", income);
		model.put("expenses", expenses);
		model.put("inventory", inven);

		/**
		 * 区域保有量分析
		 */
		List<Map<String, Object>> inventoryByRegion = statisticService
				.statInventoryByRegion();
		List<Map<String, Object>> inventoryInZheJiang = statisticService
				.statInventoryInZheJiang();

		Map<String, Object> pieMap = new HashMap<String, Object>();
		for (int i = 0; i < inventoryByRegion.size(); i++) {
			BigDecimal incomeAmount = (BigDecimal) inventoryByRegion.get(i)
					.get("am");
			BigDecimal expensesAmount = (BigDecimal) inventoryByRegion.get(i)
					.get("am2");
			incomeAmount = incomeAmount != null ? incomeAmount
					: new BigDecimal(0);
			expensesAmount = expensesAmount != null ? expensesAmount
					: new BigDecimal(0);
			String cityname = (String) inventoryByRegion.get(i).get("cn");
			if (StringUtil.isBlank(cityname)) {
				cityname = "未知";
			}
			Double inventory = incomeAmount.subtract(expensesAmount)
					.doubleValue();

			pieMap.put(cityname, inventory);
		}

		Map<String, Object> pieMap2 = new HashMap<String, Object>();
		for (int i = 0; i < inventoryInZheJiang.size(); i++) {
			BigDecimal incomeAmount = (BigDecimal) inventoryInZheJiang.get(i)
					.get("am");
			BigDecimal expensesAmount = (BigDecimal) inventoryInZheJiang.get(i)
					.get("am2");
			incomeAmount = incomeAmount != null ? incomeAmount
					: new BigDecimal(0);
			expensesAmount = expensesAmount != null ? expensesAmount
					: new BigDecimal(0);
			String cityname = (String) inventoryInZheJiang.get(i).get("cn");
			if (StringUtil.isBlank(cityname)) {
				cityname = "未知";
			}
			Double inventory = incomeAmount.subtract(expensesAmount)
					.doubleValue();

			pieMap2.put(cityname, inventory);
		}

		model.put("result", pieMap);
		model.put("result2", pieMap2);

		List<Map<String, Object>> inventoryByLimit = statisticService
				.statByRegionLimit();
		List<Map<String, Object>> inZheJiangByLimit = statisticService
				.statInZheJiangLimit();

		LinkedHashMap<String, Object> dataMap = new LinkedHashMap<String, Object>();
		LinkedHashMap<String, Object> dataMap2 = new LinkedHashMap<String, Object>();
		for (int i = 0; i < inventoryByLimit.size(); i++) {
			BigDecimal inventoryAmount = (BigDecimal) inventoryByLimit.get(i)
					.get("inven");
			inventoryAmount = inventoryAmount != null ? inventoryAmount
					: new BigDecimal(0);
			String cityname = (String) inventoryByLimit.get(i).get("cn");
			if (StringUtil.isBlank(cityname)) {
				cityname = "未知";
			}
			dataMap.put(cityname, inventoryAmount);
		}

		for (int i = 0; i < inZheJiangByLimit.size(); i++) {
			BigDecimal inventoryAmount = (BigDecimal) inZheJiangByLimit.get(i)
					.get("inven");
			inventoryAmount = inventoryAmount != null ? inventoryAmount
					: new BigDecimal(0);
			String cityname = (String) inZheJiangByLimit.get(i).get("cn");
			if (StringUtil.isBlank(cityname)) {
				cityname = "未知";
			}
			dataMap2.put(cityname, inventoryAmount);
		}
		model.put("dataMap", dataMap);
		model.put("dataMap2", dataMap2);

		/**
		 * 分类产品保有量分析
		 */
		List<Map<String, Object>> inventoryByType = statisticService
				.statInventoryByType();
		List<String> inventoryList = new ArrayList<String>();
		List<String> inventoryList2 = new ArrayList<String>();
		List<String> typenameList = new ArrayList<String>();
		List<BigDecimal> incomeAmountList2 = new ArrayList<BigDecimal>();
		List<BigDecimal> expensesAmountList2 = new ArrayList<BigDecimal>();
		String typename = null;
		String inventory = null;
		BigDecimal sumIncome = null;
		BigDecimal sumExpenses = null;

		for (int i = 0; i < inventoryByType.size(); i++) {
			BigDecimal incomeAmount = (BigDecimal) inventoryByType.get(i).get(
					"income");
			BigDecimal expensesAmount = (BigDecimal) inventoryByType.get(i)
					.get("expenses");
			expensesAmount = expensesAmount != null ? expensesAmount
					: new BigDecimal(0);
			incomeAmount = incomeAmount != null ? incomeAmount
					: new BigDecimal(0);
			Integer term = (Integer) inventoryByType.get(i).get("type");
			if (term == 7) {
				typename = "周享产品";
			} else if (term >= 20 && term <= 40) {
				typename = "月享产品";
			} else if (term >= 80 && term <= 100) {
				typename = "季享产品";
			} else if (term >= 160 && term <= 200) {
				typename = "半年期产品";
			} else {
				typename = "一年期产品";
			}

			if (!typenameList.contains(typename)) {
				Integer inventoryAmount = incomeAmount.subtract(expensesAmount)
						.intValue();
				inventory = inventoryAmount.toString();
				incomeAmountList2.add(incomeAmount);
				expensesAmountList2.add(expensesAmount);
				typenameList.add(typename);
				inventoryList2.add(inventory);
			} else {
				int ind = typenameList.indexOf(typename);
				sumIncome = incomeAmount.add(incomeAmountList2.get(ind));
				sumExpenses = expensesAmount.add(expensesAmountList2.get(ind));
				Integer inventoryAmount = incomeAmount.subtract(expensesAmount)
						.intValue() + Integer.parseInt(inventoryList2.get(ind));
				inventory = inventoryAmount.toString();

				incomeAmountList2.remove(ind);
				incomeAmountList2.add(ind, sumIncome);
				expensesAmountList2.remove(ind);
				expensesAmountList2.add(ind, sumExpenses);
				inventoryList2.remove(ind);
				inventoryList2.add(ind, inventory);
			}

		}
		for (int j = 0; j < inventoryList2.size(); j++) {
			inventoryList
					.add(typenameList.get(j) + " " + inventoryList2.get(j));
		}
		model.put("typenameList", typenameList);
		model.put("incomeAmountList2", incomeAmountList2);
		model.put("expensesAmountList2", expensesAmountList2);
		model.put("inventoryList2", inventoryList);

		return "/stat/inventory";
	}

	/**
	 * 保有量组成
	 * 
	 * @param startdate
	 * @param enddate
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "structure", method = RequestMethod.GET)
	public String structure(String startdate, String enddate, ModelMap model,
			String condition) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		DecimalFormat df = new DecimalFormat("0.0%");
		Calendar cd = Calendar.getInstance();
		if (startdate == null || enddate == null) {
			Date critical = date.parse("2015-10-01");
			if ((new Date()).getTime() > critical.getTime()) {
				cd.add(Calendar.MONTH, -12);
				startdate = date.format(cd.getTime());
				enddate = date.format(new Date());
			} else {
				startdate = "2014-10-01";
				enddate = date.format(new Date());
			}
		}

		List<Map<String, Object>> inventoryList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> intereList = new ArrayList<Map<String, Object>>();

		if ("month".equals(condition) || condition == null) {

			inventoryList = statisticService.statInventory(startdate, enddate,
					"bymonth");
			intereList = statisticService.statByIntere(startdate, enddate,
					"bymonth");
			model.put("param", "month");
		} else if ("week".equals(condition)) {

			inventoryList = statisticService.statInventory(startdate, enddate,
					"byweek");
			intereList = statisticService.statByIntere(startdate, enddate,
					"byweek");
			model.put("param", "week");
		} else {

			inventoryList = statisticService.statInventory(startdate, enddate,
					"byyear");
			intereList = statisticService.statByIntere(startdate, enddate,
					"byyear");
			model.put("param", "year");
		}
		List<String> xdateList = new ArrayList<String>();
		List<String> xdateList2 = new ArrayList<String>();
		Map<String, Long[]> yDate = new HashMap<String, Long[]>();
		Map<String, Long[]> yDate2 = new HashMap<String, Long[]>();
		/*
		 * 预处理
		 */
		for (int i = 0; i < inventoryList.size(); i++) {
			String xdate = (String) inventoryList.get(i).get("xdate");
			if (!xdateList.contains(xdate)) {
				xdateList.add(xdate);
			}

			String term = ((Integer) inventoryList.get(i).get("term"))
					.toString();
			if (!yDate.containsKey(term)) {
				yDate.put(term, null);
			}
		}

		for (int i = 0; i < intereList.size(); i++) {
			String xdate = (String) intereList.get(i).get("xdate");
			if (!xdateList2.contains(xdate)) {
				xdateList2.add(xdate);
			}

			BigDecimal intere = (BigDecimal) intereList.get(i).get("intere");
			intere = intere != null ? intere : new BigDecimal(0);
			String intereString = df.format(intere);
			if (!yDate2.containsKey(intereString)) {
				yDate2.put(intereString, null);
			}
		}
		/*
		 * 初始化yDate
		 */
		Iterator<String> iterator = yDate.keySet().iterator();
		while (iterator.hasNext()) {
			String term = iterator.next();
			Long[] value = new Long[xdateList.size()];
			for (int i = 0; i < xdateList.size(); i++) {
				value[i] = new Long(0);
			}
			yDate.put(term, value);
		}

		Iterator<String> iterator2 = yDate2.keySet().iterator();
		while (iterator2.hasNext()) {
			String intere = iterator2.next();
			Long[] value = new Long[xdateList2.size()];
			for (int i = 0; i < xdateList2.size(); i++) {
				value[i] = new Long(0);
			}
			yDate2.put(intere, value);
		}
		/*
		 * 给yDate赋值
		 */
		for (int i = 0; i < inventoryList.size(); i++) {
			String xdate = (String) inventoryList.get(i).get("xdate");
			String term = ((Integer) inventoryList.get(i).get("term"))
					.toString();
			BigDecimal inven = (BigDecimal) inventoryList.get(i).get("inven");
			inven = inven != null ? inven : new BigDecimal(0);
			Long amount = inven.longValue();
			int idx = xdateList.indexOf(xdate);
			yDate.get(term)[idx] = amount;
		}

		for (int i = 0; i < intereList.size(); i++) {
			String xdate = (String) intereList.get(i).get("xdate");
			BigDecimal intere = (BigDecimal) intereList.get(i).get("intere");
			BigDecimal inven = (BigDecimal) intereList.get(i).get("inven");
			intere = intere != null ? intere : new BigDecimal(0);
			inven = inven != null ? inven : new BigDecimal(0);
			String intereString = df.format(intere);
			Long amount = inven.longValue();
			int idx = xdateList2.indexOf(xdate);
			yDate2.get(intereString)[idx] = amount;
		}

		model.put("startdate", startdate);
		model.put("enddate", enddate);
		model.put("xdateList", xdateList);
		model.put("xdateList2", xdateList2);
		model.put("yDate", yDate);
		model.put("yDate2", yDate2);

		return "/stat/consistinventory";
	}

	/**
	 * 保有量趋势
	 * 
	 * @param startdate
	 * @param enddate
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "trend", method = RequestMethod.GET)
	public String trend(ModelMap model) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat date2 = new SimpleDateFormat("yyyy-MM");
		Calendar cd = Calendar.getInstance();
		String enddate = null;
		String fromdata = null;
		String todata = null;
		List<String> datalist = new ArrayList<String>();
		List<String> trendlist = new ArrayList<String>();
		Double trendAmount = (double) 0;
		String xdata = null;
		Date critical = date.parse("2015-10-01");

		if ((new Date()).getTime() > critical.getTime()) {
			cd.add(Calendar.MONTH, -12);
			fromdata = date.format(cd.getTime());
			todata = date.format(new Date());
			for (int i = 0; i <= 12; i++) {
				cd.set(Calendar.DAY_OF_MONTH, 1);
				cd.roll(Calendar.DAY_OF_MONTH, -1);
				enddate = date.format(cd.getTime());
				if (cd.getTime().getTime() >= date.parse(todata).getTime()) {
					xdata = date2.format(new Date());
					cd.setTime(new Date());
					cd.add(Calendar.DATE, -1);
					trendAmount = statisticService.stattrendByDate(date
							.format(cd.getTime()));
				} else {
					xdata = date2.format(cd.getTime());
					trendAmount = statisticService.stattrendByDate(enddate);
				}
				trendAmount = trendAmount != null ? trendAmount : (double) 0;

				datalist.add(xdata);
				trendlist.add(trendAmount.toString());
				cd.add(Calendar.MONTH, +1);
			}
		} else {
			fromdata = "2014-10-01";
			todata = date.format(new Date());
			List<String> monthList = getMonthBetween(fromdata, todata);
			for (int i = 0; i < monthList.size(); i++) {
				cd.setTime(date2.parse(monthList.get(i)));
				cd.set(Calendar.DAY_OF_MONTH, 1);
				cd.roll(Calendar.DAY_OF_MONTH, -1);
				enddate = date.format(cd.getTime());
				if (cd.getTime().getTime() >= date.parse(todata).getTime()) {
					xdata = date2.format(new Date());
					cd.setTime(new Date());
					cd.add(Calendar.DATE, -1);
					trendAmount = statisticService.stattrendByDate(date
							.format(cd.getTime()));
				} else {
					xdata = date2.format(cd.getTime());
					trendAmount = statisticService.stattrendByDate(enddate);
				}
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				datalist.add(xdata);
				trendlist.add(trendAmount.toString());
			}
		}

		model.put("startdate", fromdata);
		model.put("enddate", todata);
		model.put("datalist", datalist);
		model.put("trendlist", trendlist);
		model.put("param", "month");
		return "/stat/inventorytrend";
	}

	/**
	 * 保有量趋势查询
	 * 
	 * @param startdate
	 * @param enddate
	 * @param condition
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "trendbydate", method = RequestMethod.GET)
	public String trendByDate(String startdate, String enddate,
			String condition, ModelMap model) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat date2 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat date3 = new SimpleDateFormat("yyyy");
		Calendar ca = Calendar.getInstance();
		String paramdate = null;
		Double trendAmount = (double) 0;
		List<String> trendlist = new ArrayList<String>();
		String compareDate = date2.format(new Date());

		if ("month".equals(condition)) {
			List<String> monthList = getMonthBetween(startdate, enddate);
			for (int i = 0; i < monthList.size(); i++) {
				ca.setTime(date.parse(monthList.get(i)));
				ca.set(Calendar.DAY_OF_MONTH, 1);
				ca.roll(Calendar.DAY_OF_MONTH, -1);
				if (ca.getTime().getTime() >= date2.parse(compareDate)
						.getTime()
						&& date.format(new Date()).equals(
								date.format(ca.getTime()))) {
					ca.setTime(new Date());
					ca.add(Calendar.DATE, -1);
					trendAmount = statisticService.stattrendByDate(date2
							.format(ca.getTime()));
				} else {
					paramdate = date2.format(ca.getTime());
					trendAmount = statisticService.stattrendByDate(paramdate);
				}
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				trendlist.add(trendAmount.toString());
			}
			model.put("datalist", monthList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "month");

		} else if ("week".equals(condition)) {
			List<String> weekList = new ArrayList<String>();
			Date fromdate = date2.parse(startdate);
			Date todate = date2.parse(enddate);
			ca.setTime(todate);
			ca.set(Calendar.DAY_OF_WEEK, 7);
			Date lastdate2 = ca.getTime();

			ca.setTime(new Date());
			Integer compareNumber = ca.get(Calendar.WEEK_OF_YEAR);

			for (long i = fromdate.getTime(); i <= lastdate2.getTime(); i += 7
					* 24 * 60 * 60 * 1000) {
				String idate = date2.format(i);
				ca.setTime(date2.parse(idate));
				ca.set(Calendar.DAY_OF_WEEK, 7);
				ca.setTimeInMillis(ca.getTime().getTime());
				Integer weeknumber = ca.get(Calendar.WEEK_OF_YEAR);
				if (ca.getTime().getTime() >= date2.parse(compareDate)
						.getTime() && weeknumber == compareNumber) {
					paramdate = date2.format(new Date());
					ca.setTime(new Date());
					ca.add(Calendar.DATE, -1);
					trendAmount = statisticService.stattrendByDate(date2
							.format(ca.getTime()));
				} else {
					paramdate = date2.format(ca.getTime());
					trendAmount = statisticService.stattrendByDate(paramdate);
				}
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				weekList.add(weeknumber + "周");
				trendlist.add(trendAmount.toString());
			}
			model.put("datalist", weekList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "week");
		} else if ("year".equals(condition)) {
			Date fromdate = date2.parse(startdate);
			Date todate = date2.parse(enddate);
			Integer startInteger = Integer.parseInt(date3.format(fromdate));
			Integer endInteger = Integer.parseInt(date3.format(todate));
			List<String> yearList = new ArrayList<String>();
			for (int i = startInteger; i <= endInteger; i++) {
				paramdate = i + "-12-31";
				if (date2.parse(paramdate).getTime() >= date2
						.parse(compareDate).getTime()
						&& date3.format(new Date()).equals(i + "")) {
					paramdate = date2.format(new Date());
					ca.setTime(new Date());
					ca.add(Calendar.DATE, -1);
					trendAmount = statisticService.stattrendByDate(date2
							.format(ca.getTime()));
				} else {
					trendAmount = statisticService.stattrendByDate(paramdate);
				}
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				yearList.add(i + "");
				trendlist.add(trendAmount.toString());
			}
			model.put("datalist", yearList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "year");

		} else {
			List<Map<String, Object>> trend = statisticService.inventoryByDay(
					startdate, enddate);
			List<String> dayList = new ArrayList<String>();
			for (int i = 0; i < trend.size(); i++) {
				String nowdate = (String) trend.get(i).get("da");
				BigDecimal amount = (BigDecimal) trend.get(i).get("am");
				amount = amount != null ? amount : new BigDecimal(0);
				dayList.add(nowdate);
				trendlist.add(amount.toString());
			}
			model.put("datalist", dayList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "day");
		}

		return "/stat/inventorytrend";
	}

	/**
	 * 获取两个日期之间月份
	 * 
	 * @param minDate
	 * @param maxDate
	 * @return
	 * @throws ParseException
	 */
	private static List<String> getMonthBetween(String minDate, String maxDate)
			throws ParseException {
		ArrayList<String> result = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月

		Calendar min = Calendar.getInstance();
		Calendar max = Calendar.getInstance();

		min.setTime(sdf.parse(minDate));
		min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

		max.setTime(sdf.parse(maxDate));
		max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

		Calendar curr = min;
		while (curr.before(max)) {
			result.add(sdf.format(curr.getTime()));
			curr.add(Calendar.MONTH, 1);
		}

		return result;
	}

	/**
	 * 网站数据导出Excel
	 * 
	 * @param a
	 * @param b
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/websiteexport/{a}&{b}", method = RequestMethod.GET)
	public String exportWebExcel(@PathVariable String a,
			@PathVariable String b, HttpServletResponse response) {

		response.setContentType("application/vnd.ms-excel");
		response.addHeader("Content-Disposition",
				"attachment; filename=websitereport.xls");

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");

		try {
			OutputStream os = response.getOutputStream();

			SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
			String rate = null;
			String start = a;
			String end = b;
			if (a == null && b == null) {
				start = date.format(new Date());
				end = date.format(new Date());
			}

			Map<String, Map<String, Map<String, Object>>> rest = getWebsiteData(
					start, end, rate);

			ExportUtil.exportWebsiteExcel(rest, os);

			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 产品数据导出Excel
	 * 
	 * @param a
	 * @param b
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/productexport/{a}&{b}", method = RequestMethod.GET)
	public String exportProExcel(@PathVariable String a,
			@PathVariable String b, HttpServletResponse response) {

		response.setContentType("application/vnd.ms-excel");
		response.addHeader("Content-Disposition",
				"attachment; filename=productreport.xls");

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");

		try {
			OutputStream os = response.getOutputStream();

			SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
			String successrate = null;
			String start = a;
			String end = b;
			if (a == null && b == null) {
				start = date.format(new Date());
				end = date.format(new Date());
			}

			Map<String, Map<String, Map<String, Object>>> rest = getProductData(
					start, end, successrate);

			ExportUtil.exportProductExcel(rest, os);

			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 销售量现状
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "salesstatus", method = RequestMethod.GET)
	public String salesAnalyse(ModelMap model) {
		DecimalFormat df = new DecimalFormat("0.0%");

		/**
		 * 销售量现状饼图
		 */
		List<Map<String, Object>> salesByRate = statisticService
				.salesStatus("rate");
		List<Map<String, Object>> salesByRegion = statisticService
				.salesStatus("region");
		Double sales = statisticService.allIncomeAndExpense("allincome");
		Map<String, Object> pieMap = new HashMap<String, Object>();
		for (int i = 0; i < salesByRate.size(); i++) {
			BigDecimal amount = (BigDecimal) salesByRate.get(i).get("am");
			BigDecimal rate = (BigDecimal) salesByRate.get(i).get("rate");
			amount = amount != null ? amount : new BigDecimal(0);
			rate = rate != null ? rate : new BigDecimal(0);
			String term = df.format(rate.doubleValue());
			pieMap.put(term, amount);
		}

		/**
		 * 分组柱状图
		 */
		List<String> xdateList = new ArrayList<String>();
		Map<String, Long[]> yDate = new HashMap<String, Long[]>();
		/*
		 * 预处理
		 */
		for (int i = 0; i < salesByRegion.size(); i++) {
			String xdate = (String) salesByRegion.get(i).get("cn");
			if (StringUtil.isBlank(xdate)) {
				xdate = "未知";
			}
			if (!xdateList.contains(xdate)) {
				xdateList.add(xdate);
			}

			BigDecimal rate = (BigDecimal) salesByRegion.get(i).get("rate");
			rate = rate != null ? rate : new BigDecimal(0);
			String term = df.format(rate.doubleValue());
			if (!yDate.containsKey(term)) {
				yDate.put(term, null);
			}
		}
		/*
		 * 初始化yDate
		 */
		Iterator<String> iterator = yDate.keySet().iterator();
		while (iterator.hasNext()) {
			String term = iterator.next();
			Long[] value = new Long[xdateList.size()];
			for (int i = 0; i < xdateList.size(); i++) {
				value[i] = new Long(0);
			}
			yDate.put(term, value);
		}
		/*
		 * 给yDate赋值
		 */
		for (int i = 0; i < salesByRegion.size(); i++) {
			String xdate = (String) salesByRegion.get(i).get("cn");
			if (StringUtil.isBlank(xdate)) {
				xdate = "未知";
			}
			BigDecimal rate = (BigDecimal) salesByRegion.get(i).get("rate");
			rate = rate != null ? rate : new BigDecimal(0);
			String term = df.format(rate.doubleValue());
			BigDecimal inven = (BigDecimal) salesByRegion.get(i).get("am");
			inven = inven != null ? inven : new BigDecimal(0);
			Long amount = inven.longValue();
			int idx = xdateList.indexOf(xdate);
			yDate.get(term)[idx] = amount;
		}

		model.put("xdateList", xdateList);
		model.put("yDate", yDate);
		model.put("pieMap", pieMap);
		model.put("sales", sales);
		return "/stat/salesanalyse";
	}

	/**
	 * 销售量组成
	 * 
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "salesconsist", method = RequestMethod.GET)
	public String salesConsist(String startdate, String enddate,
			ModelMap model, String condition) throws ParseException {
		DecimalFormat df = new DecimalFormat("0.0%");
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		if (startdate == null || enddate == null) {
			Date critical = date.parse("2015-10-01");
			if ((new Date()).getTime() > critical.getTime()) {
				cd.add(Calendar.MONTH, -12);
				startdate = date.format(cd.getTime());
				enddate = date.format(new Date());
			} else {
				startdate = "2014-10-01";
				enddate = date.format(new Date());
			}
		}
		List<Map<String, Object>> salesList = new ArrayList<Map<String, Object>>();

		if ("month".equals(condition) || condition == null) {

			salesList = statisticService.salesConsist(startdate, enddate,
					"month");
			model.put("param", "month");
		} else if ("week".equals(condition)) {

			salesList = statisticService.salesConsist(startdate, enddate,
					"week");
			model.put("param", "week");
		} else {

			salesList = statisticService.salesConsist(startdate, enddate,
					"year");
			model.put("param", "year");
		}

		List<String> xdateList = new ArrayList<String>();
		Map<String, Long[]> yDate = new HashMap<String, Long[]>();
		/*
		 * 预处理
		 */
		for (int i = 0; i < salesList.size(); i++) {
			String xdate = (String) salesList.get(i).get("xdate");
			if (!xdateList.contains(xdate)) {
				xdateList.add(xdate);
			}

			BigDecimal rate = (BigDecimal) salesList.get(i).get("rate");
			rate = rate != null ? rate : new BigDecimal(0);
			String term = df.format(rate.doubleValue());
			if (!yDate.containsKey(term)) {
				yDate.put(term, null);
			}
		}
		/*
		 * 初始化yDate
		 */
		Iterator<String> iterator = yDate.keySet().iterator();
		while (iterator.hasNext()) {
			String term = iterator.next();
			Long[] value = new Long[xdateList.size()];
			for (int i = 0; i < xdateList.size(); i++) {
				value[i] = new Long(0);
			}
			yDate.put(term, value);
		}
		/*
		 * 给yDate赋值
		 */
		for (int i = 0; i < salesList.size(); i++) {
			String xdate = (String) salesList.get(i).get("xdate");
			BigDecimal rate = (BigDecimal) salesList.get(i).get("rate");
			rate = rate != null ? rate : new BigDecimal(0);
			String term = df.format(rate.doubleValue());
			BigDecimal inven = (BigDecimal) salesList.get(i).get("am");
			inven = inven != null ? inven : new BigDecimal(0);
			Long amount = inven.longValue();
			int idx = xdateList.indexOf(xdate);
			yDate.get(term)[idx] = amount;
		}

		model.put("startdate", startdate);
		model.put("enddate", enddate);
		model.put("xdateList", xdateList);
		model.put("yDate", yDate);

		return "/stat/salesconsist";
	}

	/**
	 * 销售量趋势
	 * 
	 * @param startdate
	 * @param enddate
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "salestrend", method = RequestMethod.GET)
	public String salesTrend(ModelMap model) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat date2 = new SimpleDateFormat("yyyy-MM");
		Calendar cd = Calendar.getInstance();
		String fromdata = null;
		String todata = null;
		List<String> datalist = new ArrayList<String>();
		List<String> trendlist = new ArrayList<String>();
		Double trendAmount = (double) 0;
		String xdata = null;
		Date critical = date.parse("2015-10-01");

		if ((new Date()).getTime() > critical.getTime()) {
			cd.add(Calendar.MONTH, -12);
			fromdata = date.format(cd.getTime());
			todata = date.format(new Date());
			for (int i = 0; i <= 12; i++) {
				xdata = date2.format(cd.getTime());
				trendAmount = statisticService
						.selectSalesByTime(xdata, "month");
				trendAmount = trendAmount != null ? trendAmount : (double) 0;

				datalist.add(xdata);
				trendlist.add(trendAmount.toString());
				cd.add(Calendar.MONTH, +1);
			}
		} else {
			fromdata = "2014-10-01";
			todata = date.format(new Date());
			List<String> monthList = getMonthBetween(fromdata, todata);
			for (int i = 0; i < monthList.size(); i++) {
				xdata = monthList.get(i);
				trendAmount = statisticService
						.selectSalesByTime(xdata, "month");
				trendAmount = trendAmount != null ? trendAmount : (double) 0;

				datalist.add(xdata);
				trendlist.add(trendAmount.toString());
			}
		}

		model.put("startdate", fromdata);
		model.put("enddate", todata);
		model.put("datalist", datalist);
		model.put("trendlist", trendlist);
		model.put("param", "month");
		return "/stat/salestrend";
	}

	/**
	 * 销售量趋势查询
	 * 
	 * @param startdate
	 * @param enddate
	 * @param condition
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "salestrendbydate", method = RequestMethod.GET)
	public String salesTrendByDate(String startdate, String enddate,
			String condition, ModelMap model) throws ParseException {
		SimpleDateFormat date2 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat date3 = new SimpleDateFormat("yyyy");
		Calendar ca = Calendar.getInstance();
		String paramdate = null;
		Double trendAmount = (double) 0;
		List<String> trendlist = new ArrayList<String>();

		if ("month".equals(condition)) {
			List<String> monthList = getMonthBetween(startdate, enddate);
			for (int i = 0; i < monthList.size(); i++) {
				paramdate = monthList.get(i);
				trendAmount = statisticService.selectSalesByTime(paramdate,
						"month");
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				trendlist.add(trendAmount.toString());
			}
			model.put("datalist", monthList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "month");

		} else if ("week".equals(condition)) {
			List<String> weekList = new ArrayList<String>();
			Date fromdate = date2.parse(startdate);
			Date todate = date2.parse(enddate);
			ca.setTime(todate);
			ca.set(Calendar.DAY_OF_WEEK, 7);
			Date lastdate2 = ca.getTime();

			for (long i = fromdate.getTime(); i <= lastdate2.getTime(); i += 7
					* 24 * 60 * 60 * 1000) {
				String idate = date2.format(i);
				ca.setTime(date2.parse(idate));
				ca.set(Calendar.DAY_OF_WEEK, 7);
				ca.setTimeInMillis(ca.getTime().getTime());
				Integer weeknumber = ca.get(Calendar.WEEK_OF_YEAR);
				if (weeknumber < 10) {
					paramdate = date3.format(ca.getTime()) + "-0" + weeknumber;
				} else {
					paramdate = date3.format(ca.getTime()) + "-" + weeknumber;
				}
				trendAmount = statisticService.selectSalesByTime(paramdate,
						"week");
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				weekList.add(weeknumber + "周");
				trendlist.add(trendAmount.toString());
			}
			model.put("datalist", weekList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "week");
		} else if ("year".equals(condition)) {
			Date fromdate = date2.parse(startdate);
			Date todate = date2.parse(enddate);
			Integer startInteger = Integer.parseInt(date3.format(fromdate));
			Integer endInteger = Integer.parseInt(date3.format(todate));
			List<String> yearList = new ArrayList<String>();
			for (int i = startInteger; i <= endInteger; i++) {
				paramdate = i + "";
				trendAmount = statisticService.selectSalesByTime(paramdate,
						"year");
				trendAmount = trendAmount != null ? trendAmount : (double) 0;
				yearList.add(paramdate);
				trendlist.add(trendAmount.toString());
			}
			model.put("datalist", yearList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "year");

		} else {
			List<Map<String, Object>> trend = statisticService
					.selectSalesByDate(startdate, enddate);
			List<String> dayList = new ArrayList<String>();
			for (int i = 0; i < trend.size(); i++) {
				String nowdate = (String) trend.get(i).get("da");
				BigDecimal amount = (BigDecimal) trend.get(i).get("am");
				amount = amount != null ? amount : new BigDecimal(0);
				dayList.add(nowdate);
				trendlist.add(amount.toString());
			}
			model.put("datalist", dayList);
			model.put("trendlist", trendlist);
			model.put("startdate", startdate);
			model.put("enddate", enddate);
			model.put("param", "day");
		}

		return "/stat/salestrend";
	}

	/**
	 * 支付网关统计
	 * 
	 * @throws ParseException
	 */
	@RequestMapping(value = "statpaygate/{a}", method = RequestMethod.GET)
	public String statPaygate(@PathVariable Integer a, String startTime,
			ModelMap model) throws ParseException {
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		String end = date.format(new Date());

		cd.add(Calendar.DATE, -1);
		String oneDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -6);
		String sevenDayAgo = date.format(cd.getTime());
		cd.add(Calendar.DATE, -23);
		String thirtyDayAgo = date.format(cd.getTime());

		String start = null;
		String param = null;
		if (a == 100) {
			end = null;
			param = "all";
			model.put("msg", "c");
			model.put("param", "a");
		} else if (a == 30) {
			start = thirtyDayAgo;
			param = "day";
			model.put("msg", "b");
		} else if (a == 7) {
			start = sevenDayAgo;
			param = "day";
			model.put("msg", "a");
		} else if (a == 1) {
			start = oneDayAgo;
			end = oneDayAgo;
			param = "day";
			model.put("msg", "d");
		} else if (a == 0) {
			start = end;
			param = "day";
		} else {
			if ("".equals(startTime)) {
				start = end;
			} else {
				start = startTime;
				end = startTime;
			}
			param = "day";
			model.put("msg", "c");
		}
		String successrate = null;

		List<BankCard> bankCard = statisticService.bankCardByDate(start, end,
				param);
		BankCard bc = new BankCard();
		bc.setBankCode("All");
		bc.setBankName("汇总");
		bankCard.add(bc);
		Map<String, Map<String, Map<String, Object>>> rest = getPayGateData(
				start, end, successrate, param);

		model.addAttribute("result", rest);
		model.put("bankCardList", bankCard);
		model.put("startTime", start);
		model.put("endTime", end);
		return "/stat/statpaygate";
	}

	/**
	 * 得到支付网关统计数据
	 * 
	 * @param start
	 * @param end
	 * @param successrate
	 * @param param
	 * @return
	 * @throws ParseException
	 */
	public Map<String, Map<String, Map<String, Object>>> getPayGateData(
			String start, String end, String successrate, String param)
			throws ParseException {

		/*
		 * 分银行数据
		 */
		List<Map<String, Object>> paygatebanklist = statisticService
				.paygatebankStat(start, end, param);// 交易总金额
		List<Map<String, Object>> highAmountlist = statisticService
				.paygateHighAmount(start, end, param);// 最高交易金额
		List<Map<String, Object>> orderlist = statisticService.paygateOrder(
				start, end, param);// 交易笔数
		List<Map<String, Object>> successOrderlist = statisticService
				.paygateSuccessOrder(start, end, param);// 成功交易笔数

		/**
		 * 总和数据
		 */
		List<Map<String, Object>> gatherPGAmount = statisticService
				.gatherPayGateAmount(start, end, param);
		List<Map<String, Object>> gatherPGHighAmount = statisticService
				.gatherPayGateHighAmount(start, end, param);
		List<Map<String, Object>> gatherPGOrder = statisticService
				.gatherPayGateOrder(start, end, param);
		List<Map<String, Object>> gatherPGSuccessOrder = statisticService
				.gatherPayGateSuccessOrder(start, end, param);

		List<PayGate> paygates = statisticService.payGateByDate(start, end,
				param);
		List<BankCard> bankCard = statisticService.bankCardByDate(start, end,
				param);
		BankCard bc = new BankCard();
		bc.setBankCode("All");
		bc.setBankName("汇总");
		bankCard.add(bc);

		String AA = null;// 交易总金额
		String HA = null;// 最大交易金额
		String DLT = null;// 交易比数
		String SDLT = null;// 成功交易比数

		Map<String, Map<String, Map<String, Object>>> rest = new LinkedHashMap<String, Map<String, Map<String, Object>>>();
		for (int j = 0; j < paygates.size(); j++) {

			String realpg = paygates.get(j).getGateName();
			Map<String, Map<String, Object>> map = new HashMap<String, Map<String, Object>>();
			for (int i = 0; i < bankCard.size(); i++) {
				Map<String, Object> valueMap = new HashMap<String, Object>();

				if ("All".equals(bankCard.get(i).getBankCode())) {
					AA = getPGIndex(gatherPGAmount, paygates.get(j)
							.getGateCode());
					HA = getPGIndex(gatherPGHighAmount, paygates.get(j)
							.getGateCode());
					DLT = getPGIndex(gatherPGOrder, paygates.get(j)
							.getGateCode());
					SDLT = getPGIndex(gatherPGSuccessOrder, paygates.get(j)
							.getGateCode());

				} else {
					AA = getPGIndex(paygatebanklist, paygates.get(j)
							.getGateCode(), bankCard.get(i).getBankCode());
					HA = getPGIndex(highAmountlist, paygates.get(j)
							.getGateCode(), bankCard.get(i).getBankCode());
					DLT = getPGIndex(orderlist, paygates.get(j).getGateCode(),
							bankCard.get(i).getBankCode());
					SDLT = getPGIndex(successOrderlist, paygates.get(j)
							.getGateCode(), bankCard.get(i).getBankCode());
				}

				if ("0".equals(DLT) || "0".equals(SDLT)) {
					successrate = "0%";
				} else {
					BigDecimal number1 = new BigDecimal(DLT);
					BigDecimal number2 = new BigDecimal(SDLT);
					Double rateNum = number2
							.divide(number1, 4, BigDecimal.ROUND_HALF_UP)
							.movePointRight(2).doubleValue();
					successrate = rateNum + "%";
				}

				valueMap.put("AA", AA);
				valueMap.put("HA", HA);
				valueMap.put("DLT", DLT);
				valueMap.put("SDLT", SDLT);
				valueMap.put("successrate", successrate);

				map.put(bankCard.get(i).getBankName(), valueMap);
			}
			rest.put(realpg, map);
		}
		return rest;
	}

	/**
	 * 支付网关数据导出Excel
	 * 
	 * @param a
	 * @param b
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/paygateexport/{a}&{b}", method = RequestMethod.GET)
	public String exportPGExcel(@PathVariable String a, @PathVariable String b,
			HttpServletResponse response) {

		response.setContentType("application/vnd.ms-excel");
		response.addHeader("Content-Disposition",
				"attachment; filename=productreport.xls");

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");

		try {
			OutputStream os = response.getOutputStream();

			String successrate = null;
			String start = a;
			String end = b;
			String param = "day";
			if ("".equals(a) && "".equals(b)) {
				param = "all";
			}

			Map<String, Map<String, Map<String, Object>>> rest = getPayGateData(
					start, end, successrate, param);

			ExportUtil.exportPGExcel(rest, os);

			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
